/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentField;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * <p>Updates content field
 * </p>
 * <p><a href="UpdateContentFieldAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.48 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action path="/core/contentField/update"
 * name="contentFieldForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentField-update, core-contentField-updateOverriden, core-contentField-updateIndexed"
 * @struts.action-forward name="inputForward"
 * path=".core.contentField.update"
 * @struts.action-forward name="viewContentField"
 * path="/core/contentField/view.do"
 * redirect="true"
 * @struts.action-forward name="listContentFields"
 * path="/core/contentField/list.do"
 * redirect="false"
 * @struts.action-forward name="callUpdateContentField"
 * path="/core/contentField/callUpdate.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentField/list.do"
 */
public final class UpdateContentFieldAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {
		ContentFieldForm contentFieldForm = (ContentFieldForm) form;

		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getOwnerId()) ) {
			ownerId = Long.valueOf(contentFieldForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		Long contentFieldId;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getId()) ) {
			contentFieldId = Long.valueOf(contentFieldForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing field ID. Returning to list");
			}
			return mapping.findForward("listContentFields");
		}

		if ( !isCancelled(request) ) {
			LookupManager lookupManager = (LookupManager) getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

			if ( owner == null ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.contentField.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			}

			String fieldIdentifier = contentFieldForm.getIdentifier();

            if (owner instanceof ContentPage || owner instanceof ActionPage) {
                Set indexedFieldIdentifiers = WebappUtil.getIndexedOverridableFieldIdentifiers(owner, request);
                Set unIndexedFieldIdentifiers = WebappUtil.getUnIndexedOverridableFieldIdentifiers(owner, request);
                Set intersection = new HashSet(indexedFieldIdentifiers);
                intersection.retainAll(unIndexedFieldIdentifiers);
                if ( !intersection.contains(fieldIdentifier) ) {
                    if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
                        if ( unIndexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldUnexpectedIndex", new ActionMessage("core.contentField.errors.unexpectedIndex"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    } else {
                        if ( indexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldIndexExpected", new ActionMessage("core.contentField.errors.indexExpected"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    }
                }
            } else if (owner instanceof Layout) {
                Layout ownerLayout = (Layout) owner;
                Set indexedFieldIdentifiers = WebappUtil.getIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                Set unIndexedFieldIdentifiers = WebappUtil.getUnIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                Set intersection = new HashSet(indexedFieldIdentifiers);
                intersection.retainAll(unIndexedFieldIdentifiers);
                if ( !intersection.contains(fieldIdentifier) ) {
                    if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
                        if ( unIndexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldUnexpectedIndex", new ActionMessage("core.contentField.errors.unexpectedIndex"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    } else {
                        if ( indexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldIndexExpected", new ActionMessage("core.contentField.errors.indexExpected"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    }
                }
            }

			if ( owner instanceof ContentPage || (owner instanceof Layout && !request.isUserInRole("core-contentField-update") || (owner instanceof ActionPage && !request.isUserInRole("core-contentField-update"))) ) {
				Set identifiers = null;
				if ( owner instanceof ContentPage || owner instanceof ActionPage ) {
                    // Updating overriden field
                    if ( !request.isUserInRole("core-contentField-updateOverriden") ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);

					if ( !identifiers.contains(fieldIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("contentFieldIncorrectIdentifier", new ActionMessage("core.contentField.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				} else {
                    // Updating indexed field
                    boolean canUpdateIndexed = request.isUserInRole("core-contentField-updateIndexed");
                    boolean canUpdateOverriden = request.isUserInRole("core-contentField-updateOverriden");
                    if ( !canUpdateIndexed && !canUpdateOverriden ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					Layout ownerLayout = (Layout) owner;
                    if (canUpdateIndexed) {
                        identifiers = WebappUtil.getIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                        if (identifiers == null) {
                            identifiers = new TreeSet();
                        }
                    }
                    if (canUpdateOverriden) {
                        identifiers.addAll(WebappUtil.getOverridableFieldIdentifiers(ownerLayout, request));
                    }
                    if ( !identifiers.contains(fieldIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("contentFieldIncorrectIdentifier", new ActionMessage("core.contentField.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				}
			} else {
                // (it's AP or Layout and user can update fields) OR (its not CP,
                // AP or Layout)
                if ( !request.isUserInRole("core-contentField-update") ) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return null;
                }
            }

			ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
			ContentField contentField = contentFieldManager.retrieveContentField(contentFieldId);
            String oldIdentifier = contentField.getIdentifier();

            if ( contentField == null ) {
				// content field not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("contentFieldNotFound", new ActionMessage("core.contentField.errors.notFound"));
				saveErrors(request, errors);
				return mapping.findForward("listContentFields");
			}

			// save field's type
			byte type = contentField.getType();

			WebappUtil.copyProperties(contentField, contentFieldForm, request);
			if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
				fieldIdentifier += "[" + contentFieldForm.getIndex() + "]";
				contentField.setIdentifier(fieldIdentifier);
			}

			// field's type cannot be changed, so set old value forcibly
			contentField.setType(type);

            boolean identifierChanged = !oldIdentifier.equals(contentField.getIdentifier());

            try {

				contentFieldManager.updateContentField(contentField, ownerId);

				// put into search index
				SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());

				//flush cache
				CacheUtil cacheUtil = CacheUtil.getInstance(request);
				cacheUtil.flushFieldIndices();

				if ( owner instanceof Layout ) {
					Layout layout = (Layout) owner;

					//add into search index for every content page of the layout.
					List contentPages = layout.getContentPages();
					for ( int i = 0; i < contentPages.size(); i++ ) {
						ContentPage contentPage = (ContentPage) contentPages.get(i);
						searchManager.reIndexPage(contentPage, request);
						cacheUtil.updateContentPageLastModifiedInCache(contentPage.getUri());
					}
					cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

				} else if ( owner instanceof Page ) {
					Page page = (Page) owner;
					searchManager.reIndexPage(page, request);
					cacheUtil.flushPageFieldValueCache(page.getUri());
					if ( page instanceof ContentPage ) {
						cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
					}

                    if (identifierChanged) {
                        // updating 'update time'
                        PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
                        page.setLastUpdatedDatetime(new Date());
                        pageManager.updatePage(page);
                    }
                }

			} catch ( BeanAlreadyExistsException e ) {
				// contentField already exists
				ActionMessages errors = new ActionMessages();
				errors.add("contentFieldAlreadyExists", new ActionMessage("core.contentField.errors.alreadyExists"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			} catch ( ObjectOptimisticLockingFailureException e ) {
				// content field was updated or deleted by another transaction
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.contentField.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("callUpdateContentField");
			}
			request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_ID_KEY, Long.valueOf(contentFieldForm.getId()));
			return mapping.findForward("viewContentField");
		} else {
			// action was cancelled - return to page with list of content fields
			String requestUrl = (String) request.getSession().getAttribute("beforeEditedFieldUrl");
			if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
				request.getSession().removeAttribute("beforeEditedFieldUrl");
				return new ActionForward(requestUrl, true);
			} else {
				return mapping.findForward("listContentFields");
			}
		}

	}
}